package com.mvvmhabit.org.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
/**
 * @Date: 2020/11/18 10:53
 * @Author:小妖
 * @Description: Fragment懒加载
 */
abstract class BaseLazyFragment<V : ViewDataBinding, VM : BaseViewModel> : BaseFragment<V, VM>() {
    //Fragment是否加载
    private var isFragmentLoad = false
    //Fragment的根布局
    private var rootView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState)
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!isFragmentLoad && userVisibleHint) {
            lazyLoadData()
            isFragmentLoad = true
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (rootView == null) {
            return
        }
        if (!isFragmentLoad && isVisibleToUser) {
            lazyLoadData()
            isFragmentLoad = true
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        isFragmentLoad = false
        rootView = null
    }

    /**
     * 懒加载数据，让子类实现
     */
    protected abstract fun lazyLoadData()
}